import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/langs/text_key.dart';
import 'package:azring/core/config/api_config.dart';
import 'package:azring/core/models/api_response.dart';
import 'package:azring/core/network/dio_client.dart';
import 'package:azring/generated/json/base/json_convert_content.dart';

abstract class ApiHelper {
  static Future<dynamic> request<T>(
      {required String path,
      DioClient? client,
      String method = 'GET',
      Map<String, dynamic>? queryParameters,
      dynamic data,
      bool isShowErrMsg = true,
      bool isShowLoading = false}) async {
    try {
      if (isShowLoading) {
        showLoading();
      }
      final response = await (client ?? DioClient()).request(
        path: path,
        method: method,
        queryParameters: queryParameters,
        data: data,
      );
      print('response.data: ${response.data}');

      // 检查是否有data字段
      if (!response.data.containsKey('data')) {
        // 没有data字段，直接解析为ApiResponse，但不转换data部分
        ApiResponse<Map<String, dynamic>> res =
            ApiResponse.fromJson(response.data, null);

        if (res.isSuccess) {
          // 对于没有data字段的成功响应，返回整个响应对象
          return response.data;
        } else {
          if (isShowErrMsg) {
            Toast.show(res.msg);
          }
          return null;
        }
      } else {
        // 有data字段，需要检查data的类型
        final responseData = response.data;
        final code = responseData['code'];
        final msg = responseData['msg'] ?? '';
        final dataField = responseData['data'];
        
        // 检查是否成功
        bool isSuccess = code == 200;
        
        if (isSuccess) {
          // 成功时，根据T的类型和data的实际类型来决定如何处理
          if (T == dynamic) {
            // 如果T是dynamic，直接返回整个响应
            return responseData;
          } else if (T.toString().contains('Map<String, dynamic>')) {
            // 如果T是Map类型，直接返回整个响应
            return responseData;
          } else {
            // 其他情况，尝试转换data字段
            try {
              return JsonConvert.fromJsonAsT<T>(dataField);
            } catch (e) {
              print('JSON转换失败: $e, 原始数据类型: ${dataField.runtimeType}');
              // 转换失败时，返回原始data字段
              return dataField;
            }
          }
        } else {
          if (isShowErrMsg) {
            Toast.show(msg);
          }
          return null;
        }
      }
    } catch (e) {
      print('API请求异常: $e');
      Toast.show("网络错误");
    } finally {
      if (isShowLoading) {
        dismissLoading();
      }
    }
    return null;
  }
}
